<template>
    <div class="container">
        <header class="navbar">
            <div class="left" @click="goBack">
                <van-icon name="arrow-left" size="20" />
            </div>
            <div class="title">
                <span class="ep_title">{{ store.comic_title }}</span>
                <span class="ep_index">第 {{ store.comic_short_title }} 话</span>
            </div>
            <div class="detail" @click="goToDetail(store.comic_id)">
                详情
            </div>
        </header>
        <div class="content" @scroll="debouncedOnScroll">
            <div v-for="(image, index) in complete_url" :key="index" class="image-box" :data-id="index + 1">
                <van-image :src="image" v-lazy="image" :title="index + 1" v-if="image"></van-image>

            </div>
            <van-loading size="30px" v-show="loading" class="loading">加载中...</van-loading>
        </div>
        <div class="status">
            <span> {{ getCurrentComicSessionIndex }} /{{ imagesNumber }}</span>
            <span> 第 {{ store.comic_short_title }} 话</span>
        </div>



        <template v-if="complete_url">
            <!-- 当是VIP的时候，显示VIP弹窗 -->
            <van-popup ref="vip" v-model:show="isVip" @click-close-icon="onClickCloseIcon"
                :close-on-click-overlay="false" :closeable="true" position="bottom" round>
                <div class="vip-content">
                    <div class="vip-title">啊哦，到付费章节了</div>
                    <div class="vip-text">APP内解锁更划算！</div>
                    <van-button class="vip-btn" round @click="openApp">前往APP</van-button>
                    <van-image :src="Knee" class="knee"></van-image>
                </div>




            </van-popup>
        </template>

    </div>
</template>
<script setup>
import { ref, computed, onMounted, useTemplateRef } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { fetchImg, fetchImgFromToken } from "@/api/index"
import { useStore } from "@/pinia/index"
const store = useStore()
const router = useRouter()
const route = useRoute()
const props = defineProps({
    // 当前章节ID
    id: {
        type: String,
    }
})
import Next from "@/assets/next.png"   //即将进入下一话
import Previous from "@/assets/previous.png"  //即将进入上一话
import Knee from "@/assets/knee.png"


const isEnd = ref(false) //当前章节是否结束
const loading = ref(false)
const finished = ref(false)

// 在 setup 中添加初始加载标志
const isInitialLoad = ref(true)

// 当前章节ID
// const chapter_id = computed(() => route.params.id )
const chapter_id = ref(route.params.id || props.id)
// 图片集合
const images = ref([])
// 图片数量
const imagesNumber = computed(() => images.value.length)
// 当前图片索引
const imageIndex = ref(0)
// 当前漫画绘画序列
const getCurrentComicSessionIndex = computed(() => imageIndex.value + 1)
//  真实图片完整URL
const complete_url = ref([])
/* 在现有代码基础上添加以下内容  */
// 添加用于追踪滚动方向和历史记录的响应式变量
const scrollPosition = ref(0)
// 添加当前方向状态
const direction = ref('down') // 'up' 或 'down'

const isVip = computed(() => store.comic_chapter_isLocked) //是否是VIP

const popup = useTemplateRef('vip')





onMounted(async () => {
    await initChapter()
});
// 初始化当前章节
const initChapter = async () => {
    loading.value = true
    console.log("当前章节id:", chapter_id.value)
    // 获取当前章节图片列表
    await getImg(chapter_id.value)
    if (images.value.length > 0) {
        // 只加载第一张图片
        await getImgFromToken(images.value[0])
        imageIndex.value = 0
        // 初始化时不需要预加载前一章节图片
    }
    loading.value = false
}
// 当前章节全部图片
const getImg = async (chapter_id) => {
    const { data: { images: details } } = await fetchImg(chapter_id)
    // console.log("details:", details)
    // detail 是一个对象数组，每个对象有个属性path，需要提取path的值, 然后将'@660w.jpg'拼接到path值的最后组成新的数组
    // console.log("images:", images.value)
    if (details.length > 0) {
        images.value = details.map(item => item.path + '@660w.jpg') //当前章节全部图片
    } else {
        images.value = []
    }
};
// 根据图片路径获取完整URL并添加到显示列表
const getImgFromToken = async (imagePath, insertAtIndex = null) => {
    if (!imagePath) {
        console.log('图片路径不存在')
        return
    }
    try {
        const { data } = await fetchImgFromToken(imagePath)
        if (data && data.length > 0 && data[0].complete_url) {
            if (insertAtIndex !== null) {
                // 在指定位置插入图片
                complete_url.value.splice(insertAtIndex, 0, data[0].complete_url)
            } else {
                // 默认添加到末尾
                complete_url.value.push(data[0].complete_url)
            }
        }
    } catch (error) {
        console.error('图片加载失败:', error)
    }
}
// 滚动事件处理
const onScroll = async (event) => {
    const { scrollTop, scrollHeight, clientHeight } = event.target

    // 初始加载时不处理滚动
    if (isInitialLoad.value) {
        // 使用更可靠的初始加载完成检测
        if (complete_url.value.length > 0) {
            // 确保至少有一张图片加载完成后再释放初始加载状态
            isInitialLoad.value = false
        } else {
            return
        }
    }


    // 判断滚动方向
    if (scrollTop > scrollPosition.value) {
        // 向下滚动
        console.log("滚动方向: 下")
        direction.value = 'down'
        await handleScrollDown(scrollTop, scrollHeight, clientHeight)
    } else if (scrollTop < scrollPosition.value) {
        // 向上滚动
        console.log("滚动方向: 上")
        direction.value = 'up'
        await handleScrollUp(scrollTop, scrollHeight, clientHeight)
    }
    // 更新滚动位置
    scrollPosition.value = scrollTop
}
// 获取下一章节ID
const getNextMenu_id = (currentId) => {
    const currentIdIndex = store.chapters_id.findIndex((itemId) => {
        return Number(itemId) === Number(currentId)
    })
    if (currentIdIndex === -1) {
        console.warn("当前章节ID在章节列表中未找到")
        return null
    }
    if (currentIdIndex === store.chapters_id.length - 1) {
        // 已经是最后一章
        return null
    }
    const nextIdIndex = currentIdIndex + 1
    // 更新当前漫画会话数
    store.set_comic_short_title(store.comic_sessions[nextIdIndex])
    return store.chapters_id[nextIdIndex]
}
// 获取前一章节ID
const getPreviousMenu_id = (currentId) => {
    const currentIdIndex = store.chapters_id.findIndex((itemId) => {
        return Number(itemId) === Number(currentId)
    })
    if (currentIdIndex === -1) {
        console.warn("当前章节ID在章节列表中未找到")
        return null
    }
    if (currentIdIndex === 0) {
        // 已经是第一章
        return null
    }
    const previousIdIndex = currentIdIndex - 1
    // 更新当前漫画会话数
    store.set_comic_short_title(store.comic_sessions[previousIdIndex])
    return store.chapters_id[previousIdIndex]
}
// 处理向下滚动
const handleScrollDown = async (scrollTop, scrollHeight, clientHeight) => {
    // 检查是否接近底部（距离底部10px以内）
    if (scrollTop + clientHeight >= scrollHeight - 10) {
        if (loading.value) return
        loading.value = true
        // 如果当前不是章节最后一张图片
        if (imageIndex.value < imagesNumber.value - 1) {
            imageIndex.value++
            await getImgFromToken(images.value[imageIndex.value])
        }
        // 如果是章节最后一张图片，需要加载下一章节
        else {
            const nextChapterId = getNextMenu_id(chapter_id.value)
            if (nextChapterId) {
                // 添加过渡图片
                complete_url.value.push(Next)
                // 切换到下一章节
                chapter_id.value = nextChapterId
                await getImg(chapter_id.value)
                // 重置索引并加载第一张图片
                if (images.value.length > 0) {
                    imageIndex.value = 0
                    await getImgFromToken(images.value[imageIndex.value])
                }
            }
        }
        loading.value = false
    }
}
// 处理向上滚动
// 修改 handleScrollUp 方法
const handleScrollUp = async (scrollTop, scrollHeight, clientHeight) => {
    // 检查是否接近顶部（距离顶部10px以内）
    if (scrollTop <= 10) {
        if (loading.value) return
        loading.value = true

        // 如果当前不是章节第一张图片
        if (imageIndex.value > 0) {
            imageIndex.value--
            // 确保要加载的图片存在
            if (images.value[imageIndex.value]) {
                await getImgFromToken(images.value[imageIndex.value])
                // 重新排序显示的图片
                const newImage = complete_url.value.pop()
                complete_url.value.unshift(newImage)
            }
        }
        // 如果是章节第一张图片，需要加载上一章节
        else {
            const previousChapterId = getPreviousMenu_id(chapter_id.value)
            if (previousChapterId) {
                // 保存当前章节信息
                const currentChapterId = chapter_id.value

                // 切换到上一章节
                chapter_id.value = previousChapterId
                await getImg(chapter_id.value)

                // 加载上一章节最后一张图片
                if (images.value.length > 0) {
                    imageIndex.value = images.value.length - 1
                    // 在现有图片前插入过渡图片和上一章节最后一张图片
                    complete_url.value.unshift(Previous)
                    await getImgFromToken(images.value[imageIndex.value], 0)
                }
            }
        }
        loading.value = false

        // 调整滚动位置
        setTimeout(() => {
            const content = document.querySelector('.content')
            if (content) {
                content.scrollTop = 20
            }
        }, 50)
    }
}
const goBack = () => {
    router.go(-1)
};
const goToDetail = (id) => {
    router.push({ path: `/detail/${id}` })
};

// 在 script setup 中添加防抖函数
const debounce = (func, wait) => {
    let timeout
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout)
            func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
    }
};
// 修改 onScroll 方法，添加防抖处理
const debouncedOnScroll = debounce(onScroll, 100);


// 关闭popup
const onClickCloseIcon = () => {
    router.go(-1)
}

</script>
<style scoped lang="scss">
.container {
    position: relative;

    .navbar {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 10;
        height: 44px;
        width: 100%;
        background-color: #000;
        color: #fff;
        display: flex;
        align-items: center;
        padding: 0 10px;

        .left {
            font-size: 16px;
        }

        .title {
            margin-left: 20px;
            display: flex;
            align-items: center;
            justify-content: space-around;

            .ep_title {
                font-size: 16px;
                overflow: hidden;
                text-overflow: ellipsis;
                flex: 1;
                white-space: nowrap;
            }

            .ep_index {
                font-size: 12px;
                margin-left: 10px;
            }
        }

        .detail {
            margin: 0 20px;
            font-size: 12px;
            border: 1px solid #fb7299;
            border-radius: 4px;
            width: 60px;
            text-align: center;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-sizing: border-box;
        }
    }

    .content {
        margin: 44px 0 0 0;
        overflow-y: scroll;
        -webkit-overflow-scrolling: touch;
        scroll-behavior: smooth;
        height: calc(100vh - 44px);

        position: relative;

        .image-box {
            font-size: 0;
        }

        .loading {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100vw;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 99;
        }
    }

    .status {
        position: fixed;
        bottom: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.6);
        color: #fff;
        display: flex;
        align-items: center;
        gap: 10px;
        justify-content: flex-start;
        font-size: 14px;
        border-top-left-radius: 4px;
        padding: 3px 6px;
    }

    :deep(.van-popup) {
        overflow: visible !important;
    }

    .vip-content {
        padding: 30px 10px;

        position: relative;
        overflow: visible;

        .vip-title {
            font-size: 18px;
        }

        .vip-text {
            font-size: 16px;
        }

        .vip-btn {

            background-color: #fb7299;
            margin-top: 20px;
            width: 100%;
        }

        .knee {
            position: absolute;
            top: 0;
            right: 20px;
            height: 100px;
            width: auto;
            margin-top: -10px;


        }
    }

}
</style>